function r = targetreturn(u,win,offs,wgts)
%TARGETRETURN Portfolio weight accuracy.
%   R = TARGETRETURN(UNIVERSE,WINDOW,OFFSET,WGTS) tests accuracy of
%   the weights returned by PORTOPT.
%
%   Inputs:
%
%      UNIVERSE - Portfolio matrix containing the total return data for a
%                 group of securities.  It is an Mx(N+1) matrix where column 1
%                 contains MATLAB date numbers and the remaining columns 
%                 are the total return data for each security.  N is the
%                 number of securities.
%      WINDOW - Number of periods of data to use to calculate frontier.
%      OFFSET - Increment in number of periods at which each frontier 
%               was generated.
%      WGTS - A (Number of assets) x (Number of curves) matrix of 
%             asset allocation weights needed to obtain the target rate of 
%             return.
%
%   Output: 
%  
%     R - The target return value for each window of data and
%     given portfolio weights.   These values should match the input target
%     return used with SELECTRETURN.
%
%   See also FRONTIER, SELECTRETURN.

%       Copyright 1995-2005 The MathWorks, Inc.
%       $Revision: 1.1.6.1 $   $Date: 2005/11/01 23:50:23 $

%Determine number of securities and curves
[numsec,numcurves] = size(wgts);

%Weights and Universe must have same dimensions
if (size(u,2)-1) ~= numsec
  error('finance:finance:targetreturn',...
        ['Number of weights for each curve must be equal to \n',...
               'the number of securities in the Universe.'])
end

%Calculate mean returns used to generate curves of frontier surface
a = zeros(numsec,numcurves);

%Subtract benchmark from data if it is given
try
  for k = 0:numcurves-1
    for i = 1:numsec
      a(i,k+1) = mean(u(end-((win-1)+(offs*k)):end-(offs*k),i+1));
    end
  end
catch
  a(i,k+1) = NaN;
end
a = fliplr(a);

%Replace NaN's with zeros 
i = find(isnan(a));
a(i) = 0;

%Back target return out of averages returns and weights
r = zeros(1,numcurves);
for i = 1:numcurves
  r(i) = sum(a(:,i) .* wgts(:,i));
end
